from urllib.request import *
from urllib.parse import *
from http.cookiejar import *

# 保存cookie的使用

headers = {
    "User-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36",
}


# 登录
# 保存cookie到文件中
def save_cookie(url, data):
    request = Request(url, data=urlencode(data).encode(), headers=headers)
    cookie_jar = MozillaCookieJar()
    handler = HTTPCookieProcessor(cookie_jar)
    opener = build_opener(handler)
    response = opener.open(request)
    cookie_jar.save("cookie.txt", ignore_discard=True, ignore_expires=True)


# 从文件中获取cookie
# 携带cookie访问页面
def use_cookie(url):
    request = Request(url, headers=headers)
    cookie_jar = MozillaCookieJar()
    cookie_jar.load("cookie.txt", ignore_discard=True, ignore_expires=True)
    handler = HTTPCookieProcessor(cookie_jar)
    opener = build_opener(handler)
    response = opener.open(request)
    print(response.read().decode())


def main():
    save_cookie("https://www.w3cschool.cn/checklogin_1", {"username": "username", "password": "password"})
    use_cookie("https://www.w3cschool.cn/my")


if __name__ == '__main__':
    main()
